<template>
  <div>
    <div ref="ongoingChart" style="height: 400px;"></div>
    <div ref="finishedChart" style="height: 400px;"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import { getCourseSelectStatistic } from "@/apis/admin";

export default {
  name: "EnrollmentStatisticsChart",
  mounted() {
    this.fetchDataAndInitChart();
  },
  methods: {
    fetchDataAndInitChart() {
      getCourseSelectStatistic().then(response => {
        const data = response.data.data.list;
        const ongoingData = data.filter(item => item.status === 1);
        const finishedData = data.filter(item => item.status === -1);
        this.initOngoingChart(ongoingData);
        this.initFinishedChart(finishedData);
      });
    },
    initOngoingChart(data) {
      const chartDom = this.$refs.ongoingChart;
      const myChart = echarts.init(chartDom);
      const option = this.getChartOption(data, '正在授课课程统计');
      myChart.setOption(option);
    },
    initFinishedChart(data) {
      const chartDom = this.$refs.finishedChart;
      const myChart = echarts.init(chartDom);
      const option = this.getChartOption(data, '已结课课程统计');
      myChart.setOption(option);
    },
    getChartOption(data, title) {
      // 构建一个索引到教师名字的映射
      const indexToTeacherMap = data.reduce((acc, item, index) => {
        acc[index] = item.teacherName; // 使用数据点的索引作为键
        return acc;
      }, {});

      return {
        title: {
          text: title,
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(function (item) {
              result += item.seriesName + ': ' + item.value;
              if (item.seriesName === '已选人数') {
                // 使用数据点的索引来查找教师名字
                const teacherName = indexToTeacherMap[item.dataIndex]; // 注意这里使用 dataIndex
                result += ' (' + '教师: ' + teacherName + ')';
              }
              result += '<br/>';
            });
            return result;
          }
        },
        legend: {
          data: ['最大容量', '已选人数']
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.courseName)
        },
        yAxis: {},
        series: [{
          name: '最大容量',
          type: 'bar',
          data: data.map(item => item.maxNum)
        }, {
          name: '已选人数',
          type: 'bar',
          data: data.map(item => item.presentNum).map((num, index) => ({
            value: num,
            dataIndex: index // 存储每个数据点的索引
          }))
        }]
      };
    }
  }
}
</script>
